package com.anzhen.interview.juc;

import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhenan on 2017-3-21.
 */
public class CountDownLatchTest {
    static CountDownLatch c = new CountDownLatch(2);

    @Test
    public void test01() throws InterruptedException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(1);
                c.countDown();
                System.out.println(2);
                try {
                    TimeUnit.SECONDS.sleep(10L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                c.countDown();
            }
        }).start();
        c.await();
        System.out.println("3");
    }

    @Test
    public void test02() throws InterruptedException {
        final CountDownLatch countDownLatch = new CountDownLatch(1000);
        for (int i = 0; i < 1000; i++) {
            final int finalI = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(finalI);
                    countDownLatch.countDown();
                    System.out.println("当前剩余 " + countDownLatch.getCount());
                }
            }).start();
        }
        countDownLatch.await();
        System.out.println("完事");
    }

}
